﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RedisLogQueueTest.CommonFunc
{
    /// <summary>
    /// 日志队列设置类
    /// </summary>
    public class LogQueueConfig
    {
        public static void RegisterLogQueue()
        {
            //ThreadPool是线程池，通过这种方式可以减少线程的创建与销毁，提高性能。
            //但实际上我不是很明白这个的运行原理，
            ThreadPool.QueueUserWorkItem(o =>
            {
                while (true)
                {
                    RedisHelper redis = new RedisHelper();
                    LoggerFunc logFunc = LoggerFactory.CreateLoggerInstance();
                    if (!logFunc.IsEmptyLogQueue())
                    {
                        //从队列的左边弹出，表示从队列头部出队
                        string logMsg = redis.ListLeftPop<string>(logFunc.QueueName);

                        if (!string.IsNullOrWhiteSpace(logMsg))
                        {
                            logFunc.errorLogger.Error(logMsg);
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000); //为避免CPU空转，在队列为空时休息1秒
                    }
                }
            });
        }
    }
}
